package org.mic.filter;

import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

@Configuration
@Component
public class SetCookieFilter extends ZuulFilter {

    @Value("${web.domain}")
    private String domain;

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
        String session = null;
        for (Pair<String, String> ps : zuulResponseHeaders) {
            if (ps.first().equals("Set-Cookie")) {
                if (!ps.second().contains("Domain=")) {
                    ps.setSecond(ps.second() + ";Domain=" + domain);
                }
                if (!ps.second().contains("Max-Age=")) {
                    ps.setSecond(ps.second() + ";Max-Age=99999999");
                }
                if (ps.second().contains("HttpOnly")) {
                    ps.setSecond(ps.second().replaceAll("HttpOnly;", ""));
                }
                if (ps.second().contains("SESSION=")) {
                    session = ps.second();
                }
            }
        }
        if (session != null) {
            ctx.addZuulResponseHeader("Set-Session", session);
        }
        return null;
    }
}